import { defineStore } from 'pinia';
import * as Cesium from 'cesium';
import image from '@/assets/chaozhan.svg';
import { getChaoZhanData } from "@/api";
import TideDialog from "@/utils/clickopen/TideDialog";
import { useScaleStore } from "@/stores/scaleStore";
export const useStationsStore = defineStore('stations', {
  state: () => ({
    viewer: null,
    stationsData: [],
    isVisible: false,
    entities: [],
    clickHandler: null ,// Store the click handler reference
    time: "2025-01-10",
    dialog: null
  }),

  actions: {
    setViewer(viewer) {
      this.viewer = viewer;
    },
    setTime(time){
      this.time=time
    },
    setStationsData(data) {
      this.stationsData = data;
    },

    toggleVisibility(visible = null) {
      if (typeof visible === 'boolean') {
        this.isVisible = visible;
      } else {
        this.isVisible = !this.isVisible;
      }

      if (this.isVisible) {
        this.loadStations();
      } else {
        this.clearStations();
      }
    },

    async loadStations() {
      this.clearStations();
      try {
        if (!this.clickHandler) {
          this.clickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
          
          this.clickHandler.setInputAction(async (click) => {
            const scaleStore = useScaleStore();
  const scale = scaleStore.currentScale || 1;
  
  // 反向计算坐标
  const adjustedPosition = new Cesium.Cartesian2(
    click.position.x / scale,
    click.position.y / scale
  );
  const pickedObject = this.viewer.scene.pick(adjustedPosition);
            // const pickedObject = this.viewer.scene.pick(click.position);
            if (Cesium.defined(pickedObject) && pickedObject.id && pickedObject.id.originalData) {
              const stationData = pickedObject.id.originalData;
              
              try {
                const response = await getChaoZhanData({
                  ctime: this.time,
                  name: stationData.name // Use the station name from the clicked entity
                });
                this.dialog=new TideDialog({
                  viewer: this.viewer,
                  position: pickedObject.id.position,
                  title: `${stationData.name}潮位数据`,
                  tideData: response.filter(item => item.name === stationData.name),
                  closeEvent: () => {
                    // Cleanup if needed
                  }
                });
              } catch (error) {
                console.error('Failed to fetch station details:', error);
              }
            }
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }

        this.stationsData.forEach(data => {
          const position = Cesium.Cartesian3.fromDegrees(data.lon, data.lat);
          
          const entity = this.viewer.entities.add({
            name: data.name,
            position,
            billboard: {
              image: image,
              width: 16,
              height: 16,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM
            },
            label: {
              text: data.name,
              font: '10pt sans-serif',
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              outlineWidth: 2,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              pixelOffset: new Cesium.Cartesian2(0, -20),
              fillColor: Cesium.Color.WHITE,
              outlineColor: Cesium.Color.BLACK,
              showBackground: true,
              backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 0.7),
              backgroundPadding: new Cesium.Cartesian2(6, 4)
            },
            originalData: data
          });
          
          this.entities.push(entity);
        });
      } catch (error) {
        console.error('加载站点图标失败:', error);
      }
    },

    clearStations() {
      // Remove entities
      this.entities.forEach(entity => {
        this.viewer.entities.remove(entity);
      });
      this.entities = [];
      
      // Remove click handler if it exists
      if (this.clickHandler) {
        this.clickHandler.destroy();
        this.clickHandler = null;
      }
      if (this.dialog) {
        this.dialog.windowClose();
      }
    }
  }
});